<?php

/*
 * Project: oCoder Framework
 * File: /models/user.php
 * Purpose: model for the account controller.
 * Author: Trung Hoang
 */

class AccountModel extends BaseModel {

    //login model
    public function login($data) {
        //processing when client click login form
        if (!empty($data)) {
            foreach ($data as $col => $value)
                $data[$col] = $this->escape($value);
            $where = 'username=' . $data['username'] . ' AND password=' . $data['password'];
            $user = $this->find($table = 'account', $orderby = 'account_id DESC', $where, $cols = '*', $limit = '1');
            if ($user) {
                if ($user->status == 0) {
                    $alert = array(
                        'class' => 'alert-warn',
                        'message' => 'Username is disabled'
                    );
                    $_SESSION['message'] = $alert;
                    return FALSE;
                }else{
                    return $user;
                }
                
            } else {
                $alert = array(
                    'class' => 'alert-error',
                    'message' => 'User or password incorect'
                );
                $_SESSION['message'] = $alert;
                return FALSE;
            }
        }

        //set var for login page
        $this->viewModel->set("pageTitle", "Login Form");
        return $this->viewModel;
    }

    //register model
    public function register($data) {

        if (!empty($data)) {
            foreach ($data as $col => $value) {
                $data[$col] = $value;
            }
            if ($data['password'] != $data['re-password']) {
                $alert = array(
                    'class' => "alert-error",
                    'message' => "Password field and Re-password field isn't matched"
                );
                $_SESSION['message'] = $alert;
                return FALSE;
            } else {
                $where = 'username=' . $this->escape($data['username']);
                $checkUser = $this->find($table = 'account', $orderby = 'account_id DESC', $where, $cols = '*', $limit = '1');
                if ($checkUser) {
                    $alert = array(
                        'class' => "alert-error",
                        'message' => "Username is exist!"
                    );
                    $_SESSION['message'] = $alert;
                    return FALSE;
                } else {
                    unset($data['re-password']);
                    return $this->save($table = 'account', $data = $data, $where = '');
                }
            }
        }

        //set var for login page
        $this->viewModel->set("pageTitle", "Register Form");
        return $this->viewModel;
    }

}

?>